<template>
	<view class="page-container">
		<!-- 顶部背景图片 -->
		<view class="home-header">
			<image class="home-top-image" src="../../static/assets/home_top.png"></image>
			<view class="header-overlay"></view>
		</view>



		<!-- 功能卡片区域 -->
		<view class="home-topcard-box">
			<view class="home-topcard">
				<view class="home-topcard-item" @click="handlerReserve">
					<view class="card-icon-wrapper reserve-icon">
						<image class="home-topcard-item-image" src="../../static/assets/combo_img.png"></image>
					</view>
					<text class="home-topcard-item-text">快速预约</text>
					<text class="home-topcard-item-desc">便捷预约用餐</text>
				</view>
				<view class="home-topcard-item" @click="handlerBindStudents">
					<view class="card-icon-wrapper bind-icon">
						<image class="home-topcard-item-image" src="../../static/assets/student_bind.png"></image>
					</view>
					<text class="home-topcard-item-text">学生绑定</text>
					<text class="home-topcard-item-desc">管理学生信息</text>
				</view>
			</view>
		</view>
		<!-- 菜单列表区域 -->
		<view class="home-content">
			<view class="home-combo-list-box">
				<!-- 学校选择区域 -->
				<view class="school-select-section">
					<view class="school-select-card" @click="showSchoolPicker">
						<view class="school-select-content">
							<view class="school-icon">🏫</view>
							<view class="school-text-content">
								<text class="school-select-label">当前学校</text>
								<text class="school-select-text">{{ selectedSchool ? selectedSchool.schoolName : '请选择学校' }}</text>
							</view>
						</view>
						<up-icon name="arrow-right" color="#999" size="16"></up-icon>
					</view>
				</view>

				<view class="home-combo-header">
					<view class="home-combo-title">
						<up-icon name="calendar" color="#6FD719" size="20"></up-icon>
						<text>下周菜单</text>
					</view>
					<view class="combo-count" v-if="data.comboList.length > 0">
						共{{ getTotalComboCount() }}道菜品
					</view>
				</view>

				<!-- 加载状态 -->
				<template v-if="isLoadingCombo">
					<view class="loading-container">
						<up-loading-icon mode="spinner" size="40" color="#6FD719"></up-loading-icon>
						<text class="loading-text">正在加载菜单...</text>
					</view>
				</template>

				<!-- 菜单列表 -->
				<template v-else-if="data.comboList.length > 0">
					<view class="combo-list-wrapper">
						<view class="home-combo-day-box" v-for="(itemData,key) in data.comboList" :key="key">
							<view class="home-combo-day-header">
								<view class="day-title">{{itemData.week}}</view>
								<view class="day-date">{{itemData.date}}</view>
							</view>
							<view class="combo-items-wrapper">
								<template v-for="(item, index) in itemData.comboList" :key="index">
									<ComboItem :item="item"></ComboItem>
								</template>
							</view>
						</view>
					</view>
				</template>

				<!-- 空数据状态 -->
				<template v-else>
					<view class="empty-container">
						<up-empty
							mode="search"
							text="暂无菜单数据"
							textColor="#999"
							iconColor="#ddd"
						>
						</up-empty>
						<view class="empty-tip">请稍后再试或联系管理员</view>
					</view>
				</template>
			</view>
		</view>

		<lqPrivacyDialog ref="privacyDialog"></lqPrivacyDialog>
	</view>

	<!-- 学校选择弹窗 -->
	<up-popup v-model:show="showSchoolModal" mode="bottom" round="20" closeable>
		<view class="school-modal">
			<view class="school-modal-header">
				<text class="school-modal-title">选择学校</text>
			</view>
			<view class="school-modal-content">
				<!-- 加载状态 -->
				<template v-if="isLoadingSchools">
					<view class="loading-container">
						<up-loading-icon mode="spinner" size="40" color="#6FD719"></up-loading-icon>
						<text class="loading-text">正在加载学校列表...</text>
					</view>
				</template>

				<!-- 学校列表 -->
				<template v-else>
					<view
						class="school-item"
						v-for="school in schoolList"
						:key="school.id"
						@click="selectSchool(school)"
						:class="{ 'school-item-selected': selectedSchool && selectedSchool.id === school.id }"
					>
						<view class="school-item-content">
							<view class="school-item-icon">🏫</view>
							<text class="school-item-name">{{ school.schoolName }}</text>
						</view>
						<up-icon
							v-if="selectedSchool && selectedSchool.id === school.id"
							name="checkmark"
							color="#6FD719"
							size="18"
						></up-icon>
					</view>
				</template>
			</view>
		</view>
	</up-popup>
</template>

<script setup>
	import {
		reactive,ref
	} from 'vue';
	import {
		onShow
	} from '@dcloudio/uni-app'
	import ComboItem from '../../components/ComboItem/index.vue'
	import lqPrivacyDialog from '../../components/lq-privacy-dialog/lq-privacy-dialog.vue';
	import {
		getSelectComboList,
		getSelectedSchool,
		setSelectedSchool
	} from '../../api/combo.js'
	import {
		login
	} from '../../api/login.js'
import {
	getSchoolList
} from '../../api/student.js'
	const privacyDialog = ref();

	// 学校选择相关数据
	const schoolList = ref([]);
	const selectedSchool = ref(null);
	const showSchoolModal = ref(false);
	const selectedSchoolId = ref(null);
	const isLoadingSchools = ref(false);
	const isLoadingCombo = ref(false);

	const handlerBindStudents = () => {
		// const userInfo = uni.getStorageSync('userInfo')
		// if (!userInfo) {
		// 	uni.showModal({
		// 		title: '登录提示',
		// 		content: '您当前暂未登录，确认是否登录?',
		// 		success(res) {
		// 			if (res.confirm) {
		// 				handlerLogin();
		// 			}
		// 		}
		// 	})
		// 	return;
		// }
		uni.navigateTo({
			url: '/pages/studentBind/studentBind'
		})

	}

	// 显示学校选择器
	const showSchoolPicker = async () => {
		if (schoolList.value.length === 0) {
			isLoadingSchools.value = true;
			try {
				schoolList.value = await getSchoolList();
			} catch (error) {
				uni.showToast({
					title: '获取学校列表失败',
					icon: 'error'
				});
				return;
			} finally {
				isLoadingSchools.value = false;
			}
		}
		showSchoolModal.value = true;
	}

	// 关闭学校选择器
	const closeSchoolPicker = () => {
		showSchoolModal.value = false;
	}

	// 加载学校列表
	const loadSchoolList = async () => {
		try {
			const schools = await getSchoolList();
			schoolList.value = schools || [];
		} catch (error) {
			console.error('加载学校列表失败:', error);
			schoolList.value = [];
		}
	};

	// 选择学校
	const selectSchool = async (school) => {
		selectedSchool.value = school;
		selectedSchoolId.value = school.id;
		uni.setStorageSync('selectedSchool', school);
		showSchoolModal.value = false;

		try {
			// 调用后端接口设置选择的学校（缓存到Redis）
			await setSelectedSchool(school.id);

			// 重新加载菜单数据，传递学校ID
			await loadComboData(school.id);

			uni.showToast({
				title: `已切换到${school.schoolName}`,
				icon: 'success'
			});
		} catch (error) {
			console.error('切换学校失败:', error);
			uni.showToast({
				title: '切换学校失败',
				icon: 'error'
			});
		}
	}

	// 加载菜单数据
	const loadComboData = async (schoolId = null) => {
		isLoadingCombo.value = true;
		try {
			// 如果没有传入schoolId，使用当前选择的学校ID
			const targetSchoolId = schoolId || selectedSchoolId.value;

			const result = await getSelectComboList(targetSchoolId);

			// 处理后端返回的数据结构
			if (result && typeof result === 'object' && result.comboList) {
				// 新的数据结构：包含selectedSchoolId和comboList
				data.comboList = result.comboList;
				selectedSchoolId.value = result.selectedSchoolId;

				// 更新选中的学校信息
				if (result.selectedSchoolId && schoolList.value.length > 0) {
					selectedSchool.value = schoolList.value.find(school => school.id === result.selectedSchoolId);
				}
			} else if (Array.isArray(result)) {
				// 兼容旧的数据结构：直接返回数组
				data.comboList = result;
			} else {
				data.comboList = [];
			}

			if (!data.comboList || data.comboList.length === 0) {
				console.log('暂无菜单数据');
			}
		} catch (error) {
			console.error('加载菜单数据失败:', error);
			uni.showToast({
				title: '加载菜单失败',
				icon: 'error'
			});
		} finally {
			isLoadingCombo.value = false;
		}
	}

	// 计算菜品总数
	const getTotalComboCount = () => {
		if (!data.comboList || data.comboList.length === 0) return 0;
		return data.comboList.reduce((total, dayData) => {
			return total + (dayData.comboList ? dayData.comboList.length : 0);
		}, 0);
	}

	const data = reactive({
		comboList: [],
	});
	const handlerLogin = () => {
		login(()=>{
		})
	}
	const handlerReserve = ()=>{
		// const userInfo = uni.getStorageSync('userInfo')
		// if (!userInfo) {
		// 	uni.showModal({
		// 		title: '登录提示',
		// 		content: '您当前暂未登录，确认是否登录?',
		// 		success(res) {
		// 			if (res.confirm) {
		// 				handlerLogin();
		// 			}
		// 		}
		// 	})
		// 	return;
		// }
		uni.navigateTo({
			url: '/pages/reserve/reserve'
		})
	}

	onShow(async () => {
		try {
			// 加载学校列表
			await loadSchoolList();

			// 从后端获取用户选择的学校
			const serverSelectedSchool = await getSelectedSchool();
			if (serverSelectedSchool) {
				selectedSchool.value = serverSelectedSchool;
				selectedSchoolId.value = serverSelectedSchool.id;
				// 同步到本地存储
				uni.setStorageSync('selectedSchool', serverSelectedSchool);
			} else {
				// 如果后端没有缓存，尝试从本地存储恢复
				const savedSchool = uni.getStorageSync('selectedSchool');
				if (savedSchool) {
					selectedSchool.value = savedSchool;
					selectedSchoolId.value = savedSchool.id;
					// 同步到后端
					try {
						await setSelectedSchool(savedSchool.id);
					} catch (error) {
						console.error('同步学校选择到后端失败:', error);
					}
				}
			}

			// 加载菜单数据（会自动使用选择的学校ID）
			await loadComboData();
		} catch (error) {
			console.error('页面初始化失败:', error);
			// 如果获取失败，仍然尝试加载菜单数据
			await loadComboData();
		}
	})
</script>

<style scoped>
	.page-container {
		background: linear-gradient(180deg, #F8FAFB 0%, #FFFFFF 100%);
		min-height: 100vh;
		width: 100%;
		overflow-x: hidden;
		box-sizing: border-box;
	}

	/* 顶部区域样式 */
	.home-header {
		position: relative;
		overflow: hidden;
	}

	.home-top-image {
		width: 100%;
		display: block;
	}

	.header-overlay {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background: linear-gradient(to top, rgba(248, 250, 251, 0.8), transparent);
	}

	/* 功能卡片区域 */
	.home-topcard-box {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
		position: relative;
		z-index: 10;
		box-sizing: border-box;
	}

	.home-topcard {
		width: 100%;
		max-width: 700rpx;
		background: linear-gradient(135deg, #FFFFFF 0%, #F8FAFB 100%);
		margin-top: -150rpx;
		border-radius: 30rpx;
		box-shadow: 0 8px 32px 0 rgba(0, 0, 0, .08);
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding: 40rpx 20rpx;
		border: 1px solid rgba(255, 255, 255, 0.8);
		position: relative;
		z-index: 10;
		box-sizing: border-box;
		overflow: hidden;
	}

	.home-topcard-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		padding: 20rpx;
		border-radius: 20rpx;
		transition: all 0.3s ease;
		position: relative;
		flex: 1;
		max-width: 50%;
		box-sizing: border-box;
	}

	.home-topcard-item:active {
		transform: scale(0.95);
		background-color: rgba(111, 215, 25, 0.05);
	}

	.card-icon-wrapper {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
		overflow: hidden;
	}

	.reserve-icon {
		background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
		box-shadow: 0 4px 16px rgba(111, 215, 25, 0.3);
	}

	.bind-icon {
		background: linear-gradient(135deg, #4A90E2 0%, #357ABD 100%);
		box-shadow: 0 4px 16px rgba(74, 144, 226, 0.3);
	}

	.home-topcard-item-image {
		width: 60rpx;
		height: 60rpx;
		filter: brightness(0) invert(1);
	}

	.home-topcard-item-text {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
		margin-bottom: 4rpx;
	}

	.home-topcard-item-desc {
		font-size: 24rpx;
		color: #999;
		text-align: center;
	}

	/* 内容区域 */
	.home-content {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 30rpx;
		box-sizing: border-box;
	}

	.home-combo-list-box {
		width: 100%;
		max-width: 700rpx;
		background: linear-gradient(135deg, #FFFFFF 0%, #FAFBFC 100%);
		margin-top: 40rpx;
		border-radius: 30rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 50rpx;
		box-shadow: 0 8px 32px 0 rgba(0, 0, 0, .06);
		border: 1px solid rgba(255, 255, 255, 0.8);
		box-sizing: border-box;
		overflow: hidden;
	}

	/* 学校选择区域样式（在菜单内） */
	.school-select-section {
		margin-bottom: 30rpx;
		padding-bottom: 30rpx;
		border-bottom: 2rpx solid #F5F7FA;
	}

	.school-select-card {
		background: linear-gradient(135deg, #F8FAFB 0%, #FFFFFF 100%);
		border-radius: 20rpx;
		padding: 24rpx 30rpx;
		box-shadow: 0 4px 16px 0 rgba(0, 0, 0, .04);
		display: flex;
		align-items: center;
		justify-content: space-between;
		border: 1px solid rgba(255, 255, 255, 0.8);
		transition: all 0.3s ease;
	}

	.school-select-card:active {
		transform: scale(0.98);
		box-shadow: 0 2px 8px 0 rgba(0, 0, 0, .08);
	}

	.school-select-content {
		display: flex;
		align-items: center;
		flex: 1;
		gap: 16rpx;
	}

	.school-icon {
		font-size: 28rpx;
		width: 50rpx;
		height: 50rpx;
		background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2px 8px rgba(111, 215, 25, 0.3);
	}

	.school-text-content {
		display: flex;
		flex-direction: column;
		gap: 4rpx;
	}

	.school-select-label {
		font-size: 24rpx;
		color: #999;
	}

	.school-select-text {
		font-size: 28rpx;
		color: #333;
		font-weight: 600;
	}

	.home-combo-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 30rpx;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #F5F7FA;
	}

	.home-combo-title {
		display: flex;
		align-items: center;
		gap: 12rpx;
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
	}

	.combo-count {
		font-size: 24rpx;
		color: #999;
		background-color: #F5F7FA;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}

	.combo-list-wrapper {
		margin-top: 20rpx;
	}

	.home-combo-day-box {
		margin-bottom: 40rpx;
	}

	.home-combo-day-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
		padding: 20rpx 24rpx;
		background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
		border-radius: 20rpx;
		box-shadow: 0 4px 16px rgba(111, 215, 25, 0.2);
	}

	.day-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #FFFFFF;
	}

	.day-date {
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.9);
	}

	.combo-items-wrapper {
		padding: 0 10rpx;
		width: 100%;
		box-sizing: border-box;
		overflow: hidden;
	}



	/* 学校选择弹窗样式 */
	.school-modal {
		background: linear-gradient(135deg, #FFFFFF 0%, #F8FAFB 100%);
		border-radius: 30rpx 30rpx 0 0;
		max-height: 80vh;
		overflow: hidden;
	}

	.school-modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx;
		border-bottom: 2rpx solid #F5F7FA;
		background-color: #FFFFFF;
	}

	.school-modal-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #333;
	}

	.school-modal-close {
		font-size: 30rpx;
		color: #666;
		padding: 10rpx 20rpx;
		border-radius: 20rpx;
		background-color: #F5F7FA;
		transition: all 0.3s ease;
	}

	.school-modal-close:active {
		background-color: #E8EAED;
		transform: scale(0.95);
	}

	.school-modal-content {
		max-height: 60vh;
		overflow-y: auto;
		padding: 20rpx 0;
	}

	.school-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 40rpx;
		margin: 0 20rpx 16rpx;
		border-radius: 20rpx;
		background-color: #FFFFFF;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
		transition: all 0.3s ease;
	}

	.school-item:active {
		transform: scale(0.98);
		background-color: #F8FAFB;
	}

	.school-item-selected {
		background: linear-gradient(135deg, rgba(111, 215, 25, 0.1) 0%, rgba(91, 192, 22, 0.05) 100%);
		border: 2rpx solid rgba(111, 215, 25, 0.3);
	}

	.school-item-content {
		display: flex;
		align-items: center;
		gap: 16rpx;
	}

	.school-item-icon {
		font-size: 28rpx;
		width: 50rpx;
		height: 50rpx;
		background: linear-gradient(135deg, #6FD719 0%, #5BC016 100%);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2px 8px rgba(111, 215, 25, 0.3);
	}

	.school-item-name {
		font-size: 32rpx;
		color: #333;
		font-weight: 500;
	}

	/* 加载状态样式 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 20rpx;
		background: linear-gradient(135deg, #F8FAFB 0%, #FFFFFF 100%);
		border-radius: 20rpx;
		margin: 20rpx 0;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
		margin-top: 24rpx;
		font-weight: 500;
	}

	/* 空数据状态样式 */
	.empty-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 80rpx 20rpx;
		background: linear-gradient(135deg, #F8FAFB 0%, #FFFFFF 100%);
		border-radius: 20rpx;
		margin: 20rpx 0;
	}

	.empty-tip {
		font-size: 26rpx;
		color: #999;
		margin-top: 20rpx;
		text-align: center;
	}

	/* 全局动画效果 */
	.home-topcard,
	.school-select-card,
	.home-combo-list-box {
		animation: fadeInUp 0.6s ease-out;
	}

	@keyframes fadeInUp {
		from {
			opacity: 0;
			transform: translateY(30rpx);
		}
		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/* 响应式设计 */
	@media screen and (max-width: 750rpx) {
		.home-topcard-box {
			padding: 0 20rpx;
		}

		.home-topcard {
			margin-top: -120rpx;
			padding: 30rpx 15rpx;
		}

		.home-topcard-item {
			padding: 15rpx;
			max-width: 48%;
		}

		.card-icon-wrapper {
			width: 100rpx;
			height: 100rpx;
		}

		.home-topcard-item-image {
			width: 50rpx;
			height: 50rpx;
		}

		.home-topcard-item-text {
			font-size: 28rpx;
		}

		.home-content {
			padding: 0 20rpx;
		}

		.home-combo-list-box {
			padding: 30rpx 20rpx;
		}

		.school-select-card {
			padding: 20rpx 24rpx;
		}

		.school-select-text {
			font-size: 26rpx;
		}

		.combo-items-wrapper {
			padding: 0 5rpx;
		}
	}
</style>